package com.region.http.client.resolver.result;

import com.region.common.utils.ReflectUtils;
import com.region.http.client.config.ClientConfig;
import com.region.http.client.exception.NotFoundResultResolverException;
import com.region.http.client.model.ResponseData;
import com.region.http.client.utils.IOUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.Type;

/**
 * The binary result resolver
 *
 * @author liujieyu
 * @date 2022/12/2
 */
public class BinaryResultResolver extends AbstractResultResolver {

    public BinaryResultResolver(ClientConfig config) {
        this.setConfig(config);
    }

    /**
     * Currently only supports File, byte arrays and InputStream objects.
     */
    @Override
    public boolean isResolver(Type type) {
        Class<?> returnClass = ReflectUtils.transform(type);
        return File.class.isAssignableFrom(returnClass) ||
                byte[].class.isAssignableFrom(returnClass) ||
                InputStream.class.isAssignableFrom(returnClass);
    }

    @Override
    public Object resolver(ResponseData responseData) throws Throwable {
        Class<?> returnClass = ReflectUtils.transform(responseData.getType());
        if (byte[].class.isAssignableFrom(returnClass)) {
            return responseData.getBody();
        } else if (File.class.isAssignableFrom(returnClass)) {
            return IOUtils.writeToFileByBytes(getCacheTmpFilePath(), responseData.getBody());
        } else if (InputStream.class.isAssignableFrom(returnClass)) {
            File tempFile = IOUtils.writeToFileByBytes(getCacheTmpFilePath(), responseData.getBody());
            return new FileInputStream(tempFile);
        } else {
            throw new NotFoundResultResolverException("Not Found Result Resolver");
        }
    }

    @Override
    public int getPriority() {
        return 50;
    }
}
